package com.spzx.channel.service.impl;

import com.spzx.channel.service.TestService;

import com.spzx.common.core.utils.uuid.UUID;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Service
public class TestServiceImpl implements TestService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    //同步锁解决单个微服务多线程安全问题
    public Long t1() {
        //分布锁解决微服务集群多线程安全问题
        String uuid = UUID.randomUUID().toString();
        Long num = 0L;
        //设置锁的过期时间，防止锁无法被释放，将uuid作为锁的值，保证每个线程删除的是自己的锁
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 10, TimeUnit.SECONDS);
        //抢到锁执行
        if (Boolean.TRUE.equals(lock)) {
            String l = stringRedisTemplate.opsForValue().get("num");
            num = Long.parseLong(l);
            num++;
            System.out.println(num);
            stringRedisTemplate.opsForValue().set("num", String.valueOf(num));
            //释放锁,使用lua脚本保证原子性
            String scriptString = "if redis.call(\"get\",KEYS[1]) == ARGV[1]\n" +
                    "then\n" +
                    "    return redis.call(\"del\",KEYS[1])\n" +
                    "else\n" +
                    "    return 0\n" +
                    "end";
            DefaultRedisScript<Long> script = new DefaultRedisScript<>();
            script.setScriptText(scriptString);
            script.setResultType(Long.class);
            stringRedisTemplate.execute(script, List.of("lock"), uuid);
        }else {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            t1();
        }

        return num;
    }
}
